package com.zwb.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.zwb.boot.common.R;
import com.zwb.boot.common.utils.RedisUtils;
import com.zwb.boot.dto.DishDto;
import com.zwb.boot.entity.Dish;
import com.zwb.boot.entity.DishFlavor;
import com.zwb.boot.service.CategoryService;
import com.zwb.boot.service.DishFlavorService;
import com.zwb.boot.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 头发又黑又长
 * @Date 2022/7/22 20:41
 * @email zwb15083976291@163.com
 */

/**
 * 菜品管理
 */
@Api("菜品管理")
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService flavorService;

    @Autowired
    private CategoryService categoryService;




    /* redis 缓存 */

    @Autowired
    private RedisUtils redisUtils;

    @Autowired(required = false)
    private ObjectMapper jsonMapper;

    @Value("#{new Long(${redisCache.timeOut})}")
    private Long cacheTimeOut;

    @Value("${redisCache.dishCachePrefix}")
    private String dishCachePrefix;


    /**
     * 保存菜品
     *
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "保存菜品接口")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        System.out.println(dishDto);
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 获取菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "获取菜品信息接口")
    @GetMapping("/page")
    public R<Page<DishDto>> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name) {

        Page<Dish> dishPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(!ObjectUtils.isEmpty(name), Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, lambdaQueryWrapper);

        // 返回 DishDto
        Page<DishDto> dishDtoPage = new Page<>();
        // 使用  BeanUtils 进行 拷贝， 第三个参数是忽略属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        // 将 dish 对象转换成功 dishDto 对象
        List<DishDto> collect = dishPage.getRecords().stream().map(dish ->
        {
            DishDto dishDto = new DishDto();
            // 拷贝属性
            BeanUtils.copyProperties(dish, dishDto);
            // 查询 categoryName
            dishDto.setCategoryName(categoryService.getById(
                    dishDto.getCategoryId()).getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(collect);

        return R.success(dishDtoPage);
    }


    /**
     * 通过id 查询 菜品的详细信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询菜品的详细信息接口")
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.findByIdWithFlavor(id);
        return R.success(dishDto);

    }


    /**
     * 更新菜品信息
     *
     * @param dishDto
     * @return
     */
    @ApiOperation(value = "更新菜品信息接口")
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("更新菜品成功");
    }


    /**
     * 修改菜品停用或者启用
     *
     * @param statusType
     * @param ids
     * @return
     */
    @ApiOperation(value = "修改菜品停用或者启用接口")
    @PostMapping("/status/{statusType}")
    public R<String> updateStatus(
            @PathVariable Integer statusType,
            @RequestParam List<Long> ids) {
        if (!Arrays.asList(1, 0).contains(statusType)) {
            return R.error("错误的请求");
        }

        // 删除缓存
        dishService.listByIds(ids).stream().forEach(item -> {
            redisUtils.del(dishCachePrefix + item.getCategoryId());
        });

        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId, ids)
                .set(Dish::getStatus, statusType);
        dishService.update(updateWrapper);

        return R.success("修改状态成功");
    }

    /**
     * 删除菜品数据
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除菜品接口")
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        dishService.deleteWithFlavors(ids);
        return R.success("删除成功");
    }

    /**
     * 分类 id 查询菜品信息
     *
     * @param categoryId
     * @return
     */
    @ApiOperation("分类id查询菜品信息")
    @GetMapping("/list")
    public R<List<DishDto>> list(@RequestParam("categoryId") Long categoryId) throws JsonProcessingException {
        List<DishDto> collect = null;
        Object cacheData = redisUtils.get(dishCachePrefix + categoryId);
        if (!ObjectUtils.isEmpty(cacheData)) {
            collect = (List<DishDto>) cacheData;
            return R.success(collect);
        }
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId)
                .eq(Dish::getStatus, 1)// 起售的菜品
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);

        collect = dishService.list(wrapper).stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
            dishDto.setFlavors(flavorService.list(queryWrapper));
            return dishDto;
        }).collect(Collectors.toList());

        // 缓存到 redis中
        if (!ObjectUtils.isEmpty(collect)) {
            redisUtils.setWithExpir(dishCachePrefix + categoryId, collect, cacheTimeOut);
        }
        return R.success(collect);

    }

}
